package it.itsvil.ejb.mdb;

import java.io.File;

import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.xml.transform.stream.StreamSource;

import net.sf.saxon.s9api.*;

public class SimpleTopicXLST implements MessageDrivenBean, MessageListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private MessageDrivenContext ctx = null;

	public SimpleTopicXLST() {
	}

	public void setMessageDrivenContext(MessageDrivenContext ctx) {
		this.ctx = ctx;
	}

	public void ejbCreate() {
	}

	public void ejbRemove() {
	}

	public void onMessage(Message msg) {
		ObjectMessage om = (ObjectMessage) msg;
		try {
			Processor proc = new Processor(false);
			XsltCompiler comp = proc.newXsltCompiler();

			XsltExecutable exp = comp.compile(new StreamSource(new File(
					"/opt/jboss-5.1.0.GA/upload/book.xsl")));
			XdmNode source = proc.newDocumentBuilder().build(
					new StreamSource(om.getObject().toString()));
			String filePath = msg.getStringProperty("filePath");
			Serializer out = proc.newSerializer(new File(filePath + ".html"));
			out.setOutputProperty(Serializer.Property.METHOD, "html");
			out.setOutputProperty(Serializer.Property.INDENT, "yes");
			XsltTransformer trans = exp.load();
			trans.setInitialContextNode(source);
			//QName paramName = new QName("in");
			//trans.setParameter(paramName, new XdmAtomicValue("prova"));
			trans.setDestination(out);
			trans.transform();

			System.out.println("Output written");

		} catch (SaxonApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}